package com.turtle.controller;

import com.turtle.constant.EsConst;
import com.turtle.entity.sql.EsBlog;
import com.turtle.service.EsSearchService;
import com.turtle.vo.ResultBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @author lijiayu
 * @date 2020/7/23
 * @description
 */
@RequestMapping("/search")
@RestController
public class ElasticSearchController {
    @Autowired
    private EsSearchService esSearchService;

    @GetMapping
    public ResultBody search(@RequestParam("keyword") String keyword,
                             @RequestParam(value = "page",defaultValue = "1") Integer page,
                             @RequestParam(value = "size",defaultValue = "10") Integer size,
                             @RequestParam(value = "isHigh",defaultValue = "true") Boolean isHigh){
        List<EsBlog> esBlogs = esSearchService.matchQuery(EsConst.BLOG_INDEX, keyword, page, size, isHigh);
        return ResultBody.result(esBlogs);
    }

    @GetMapping("/init")
    public ResultBody init(){
        try {
            if(!esSearchService.isExit(EsConst.BLOG_INDEX)){
                esSearchService.createIndex(EsConst.BLOG_INDEX);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return ResultBody.success();
    }
}
